package com.ljf.order.client;

import com.example.demo.client.ProductClient;
import com.example.demo.dataobject.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: Ljf
 * @Date : 2019/2/15 23:40
 * @Description :
 */
@RestController
@Slf4j
public class ClientController {
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ProductClient productClient;

    @GetMapping("/getProductMsg")
    public String getProductMsg() {
        String response = "";
    /*     //第一种方式,直接使用 restTemplate（url已知，写死）  RestTemplate restTemplate=new RestTemplate();
        // response= restTemplate.getForObject("http://localhost:8080/msg", String.class);

        //第二种方式 （注入 LoadBalancerClient通过应用名获取url，然后在使用）
        ServiceInstance product = loadBalancerClient.choose("PRODUCT");
        String url = String.format("http://%s:%s", product.getHost(), product.getPort() + "/msg");
        response = restTemplate.getForObject(url, String.class);

        //第三种方式 ,在 RestTemplateConfig 种，已经将RestTemplate注册为Bean,不需要手动new RestTemplate();
        response = restTemplate.getForObject("http://PRODUCT/msg", String.class);*/
        log.info("response={}", response);
        return response;
    }

    @GetMapping("/getProductsOrder")
    public List<ProductInfoOutput> getProductsOrder() {
        List<ProductInfoOutput> productInfoOutputs = productClient.listForOrder(Arrays.asList("1"));
        log.info("商品是:{}", productInfoOutputs);
        return productInfoOutputs;
    }

    @GetMapping("/decreaseStock")
    public String decreaseStock() {
        productClient.decreaseStock(null);
        log.info("扣除执行");
        return "ok";
    }


}
